package com.fabriciojf.util;

import java.io.*;

/**
 * classe para leitura de registros atraves da classe preferences
 * exemplo:
 * System.out.println(
 *    RegistryCS.getRegistryValue(
 *      "HKLM\\SYSTEM\\ControlSet001\\services\\Tomcat6\\ImagePath"));
 * @author fabricio
 * @since 18/03/2010
 * @version 1.0
 */
public class RegistryCS {

    private final String REGQUERY_UTIL = "REG QUERY ";
    
    /**
     *  singleton
     */
    private static RegistryCS instance = new RegistryCS();

    public static RegistryCS getInstance() {
        return instance;
    }

    public static String getRegistryValue(String key) {
        String result = "";
        try {

            File file = File.createTempFile("realhowto", ".vbs");
            file.deleteOnExit();
            FileWriter fw = new java.io.FileWriter(file);

            String vbs = "Dim WSHShell \n" 
                    + "Set WSHShell = WScript.CreateObject(\"WScript.Shell\")\n"
                    + "WScript.Echo _ \n"
                    + "WSHShell.RegRead(\""
                    + key + "\") \n" + "Set WSHShell = Nothing \n";
            fw.write(vbs);
            fw.close();

            Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
            BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
            
            String line;
            while ((line = input.readLine()) != null) {
                result += line;
            }
            input.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.trim();
    }

    static class StreamReader extends Thread {

        private InputStream is;
        private StringWriter sw;

        StreamReader(InputStream is) {
            this.is = is;
            sw = new StringWriter();
        }

        @Override
        public void run() {
            try {
                int c;
                while ((c = is.read()) != -1) {
                    sw.write(c);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        String getResult() {
            return sw.toString();
        }
    }
}
